// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <atomic>
#include <memory>

#include <nebula/testing/ktest_util.h>
#include <nebula/future/async_generator.h>
#include <nebula/future/future.h>

namespace nebula {
namespace util {

template <typename T>
AsyncGenerator<T> AsyncVectorIt(std::vector<T> v) {
  return create_vector_generator(std::move(v));
}

template <typename T>
AsyncGenerator<T> FailAt(AsyncGenerator<T> src, int failing_index) {
  auto index = std::make_shared<std::atomic<int>>(0);
  return [src, index, failing_index]() {
    auto idx = index->fetch_add(1);
    if (idx >= failing_index) {
      return Future<T>::make_finished(turbo::invalid_argument_error("XYZ"));
    }
    return src();
  };
}

template <typename T>
AsyncGenerator<T> SlowdownABit(AsyncGenerator<T> source) {
  return create_mapped_generator(std::move(source), [](const T& res) {
    return SleepABitAsync().Then([res]() { return res; });
  });
}

template <typename T>
class TrackingGenerator {
 public:
  explicit TrackingGenerator(AsyncGenerator<T> source)
      : state_(std::make_shared<State>(std::move(source))) {}

  Future<T> operator()() {
    state_->num_read++;
    return state_->source();
  }

  int num_read() { return state_->num_read.load(); }

 private:
  struct State {
    explicit State(AsyncGenerator<T> source) : source(std::move(source)), num_read(0) {}

    AsyncGenerator<T> source;
    std::atomic<int> num_read;
  };

  std::shared_ptr<State> state_;
};

}  // namespace util
}  // namespace nebula
